class TreeNode {
    val: number
    left: TreeNode | null
    right: TreeNode | null
    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = (val===undefined ? 0 : val)
        this.left = (left===undefined ? null : left)
        this.right = (right===undefined ? null : right)
    }
}
const tree4 = new TreeNode(4,null,null)
const tree3 = new TreeNode(3,null,null)
const tree2 = new TreeNode(2,tree4,null)
const tree1 = new TreeNode(1,tree2,tree3)


function tree2str(root: TreeNode | null): string {
    if (!root) {
        return ''
    }else if(root?.right && root?.left){
        return (root as TreeNode).val+'('+tree2str(root?.left ?? null)+')'+'('+tree2str(root?.right ?? null)+')'
    }else if(root?.left) {
        return (root as TreeNode).val+'('+tree2str(root?.left ?? null)+')'
    }else if(root?.right) {
        return (root as TreeNode).val+'()'+'('+tree2str(root?.right ?? null)+')'
    }else {
        return (root as TreeNode).val.toString()
    }
};

// function tree(root: TreeNode | null): string {
//     if (root?.val != undefined) {
//         return ''root.val
//     }
//     if (root?.left != undefined) {
//         str = str + '(' + tree(root.left,str)
//     }
//     if (root?.right != undefined) {
//         str =  str + tree(root.right,str) + ')'
//     }
    
//     console.log(str)
//     return str
// }

console.log(tree2str(tree1))